using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Browser;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Navigation;
using BTB.ApplicationStateServices;
using BTB.BTBServices;
using BTB.InventoryServices;
using BTB.ItemServices;
using BTB.PurchaseOrderServices;
using BTB.SatuanServices;
using BTB.SupplierServices;
using BTB.WarehouseServices;
using Lib;
using Lib.Approval;
using Lib.Helper;
using Lib.Mail;
using MSIACCSL2;
using MSIACCSL2.Command;
using WcfService1.DTO;
using GetListByCriteriaCompletedEventArgs = BTB.BTBServices.GetListByCriteriaCompletedEventArgs;
using GetListCompletedEventArgs = BTB.BTBServices.GetListCompletedEventArgs;
using SaveCompletedEventArgs = BTB.BTBServices.SaveCompletedEventArgs;
using SendEmailCompletedEventArgs = BTB.BTBServices.SendEmailCompletedEventArgs;

namespace BTB
{
    public class BTBViewModel : ViewModelBase
    {
        #region Delegates

        public delegate void Completed(Object param);

        #endregion

        private static Search frmSearch;
        private static string OrderType;
        private static string PropertySort;
        public static Mode mode;
        private static FrmAdd frmAdd;
        public static Completed OnSearchCompleted;
        private static NavigationService _NavigationService;
        private readonly AplicationStateServicesClient ApplicationService;
        private readonly ItemServicesClient ItemClient;
        private readonly PurchaseOrderServicesClient PurchaseOrderClient;
        private readonly SatuanServicesClient SatuanClient;
        private readonly SupplierServicesClient SupplierClient;
        private readonly WarehouseServicesClient WarehouseServicesClient;

        private readonly ValidationHandler validationHandler;
        private int CurrentPage;
        private bool IsUsed;
        private PurchaseOrderDTO POTemp;
        private ObservableCollection<int> Pages;
        private BTBDTO _BTB;
        private PagedCollectionView _BTBs;
        private BTBDetailDTO _BtbDetailCurrent;
        private bool _IsBusy;
        private bool _IsEnabled;
        private ObservableCollection<ItemDTO> _Items;
        private bool _NoLogfocus;
        private ObservableCollection<PurchaseOrderDTO> _PurchaseOrders;
        private ObservableCollection<SatuanDTO> _SatuanPacks;
        private ObservableCollection<SatuanDTO> _SatuanUnits;
        private ObservableCollection<SupplierDTO> _Suppliers;
        private ObservableCollection<WarehouseDTO> _Warehouses;
        private List<string> _errors;
        private Visibility _messageVisibility;
        private PagedCollectionView _pageSources;
        private BTBServicesClient client;
        private Dictionary<string, object> criteria;
        private string expression;

        public BTBViewModel()
        {
            WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
            IsEnabled = true;

            if (!DesignerProperties.IsInDesignTool)
            {
                client = new BTBServicesClient();
                SatuanClient = new SatuanServicesClient();
                WarehouseServicesClient = new WarehouseServicesClient();
                OnPageChanged = new DelegateCommand(PageIndexChanged, CanPageIndexChanged);
                Save = new DelegateCommand(SaveBTB, CanSave);
                New = new DelegateCommand(NewBTB, CanNew);
                Unload = new DelegateCommand(Release, CanUnload);
                SearchCommand = new DelegateCommand(SearchBTB, CanSearch);
                SearchResultCommand = new DelegateCommand(SearchResult, CanSearchResult);
                CancelCommand = new DelegateCommand(Cancel, CanCancelCommand);
                GetPOCommand = new DelegateCommand(GetPO, CanGetPOCommand);
                validationHandler = new ValidationHandler();
                MessageVisibility = Visibility.Collapsed;
                PurchaseOrderClient = new PurchaseOrderServicesClient();
                SupplierClient = new SupplierServicesClient();
                ItemClient = new ItemServicesClient();
                ApplicationService = new AplicationStateServicesClient();
                LoadDetailFromFileCommand = new DelegateCommand(LoadDetailFromFile, CanLoadDetailFromFile);

                if (mode == Mode.Edit)
                {
                    PrepareEdit();
                }
                else if (mode == Mode.Search)
                {
                    BTB = new BTBDTO();
                    BTB.TglBtb = null;
                    GetPurchaseOrderList();
                    GetSupplierList();
                }
                else if (mode == Mode.Add)
                {
                    PrepareAdd();
                }
                else
                {
                    GetList(1, null);
                }
            }
        }


        public PagedCollectionView BTBs
        {
            get { return _BTBs; }

            private set
            {
                if (BTBs == value) return;
                _BTBs = value;
                int i = (CurrentPage*30);
                foreach (object BTB in BTBs)
                {
                    i += 1;

                    ((BTBDTO) BTB).No = i;
                }
                FirePropertyChanged("BTBs");
                BTBs.CollectionChanged += BTB_CollectionChanged;
            }
        }

        public PagedCollectionView PageSources
        {
            get { return _pageSources; }
            private set
            {
                if (PageSources == value) return;
                _pageSources = value;
                FirePropertyChanged("PageSources");
            }
        }


        public ObservableCollection<PurchaseOrderDTO> PurchaseOrders
        {
            get { return _PurchaseOrders; }
            private set
            {
                if (PurchaseOrders == value) return;
                _PurchaseOrders = value;
                FirePropertyChanged("PurchaseOrders");
            }
        }


        public ObservableCollection<SupplierDTO> Suppliers
        {
            get { return _Suppliers; }
            private set
            {
                if (Suppliers == value) return;
                _Suppliers = value;
                FirePropertyChanged("Suppliers");
            }
        }


        public bool IsBusy
        {
            get { return _IsBusy; }
            internal set
            {
                _IsBusy = value;
                FirePropertyChanged("IsBusy");
            }
        }

        public bool IsEnabled
        {
            get { return _IsEnabled; }
            internal set
            {
                _IsEnabled = value;
                FirePropertyChanged("IsEnabled");
            }
        }

        public long RecordCount { get; set; }

        //Buat binding ke child form waktu mau edit
        public BTBDTO BTB
        {
            get { return _BTB; }
            private set
            {
                if (BTB == value) return;
                _BTB = value;
                FirePropertyChanged("BTB");
            }
        }

        public BTBDetailDTO BtbDetailCurrent
        {
            get { return _BtbDetailCurrent; }
            private set
            {
                if (BtbDetailCurrent == value) return;
                _BtbDetailCurrent = value;
                FirePropertyChanged("BtbDetailCurrent");
            }
        }

        public ObservableCollection<ItemDTO> Items
        {
            get { return _Items; }
            set
            {
                if (Items == value) return;
                _Items = value;
                FirePropertyChanged("Items");
            }
        }

        public ObservableCollection<SatuanDTO> SatuanPacks
        {
            get { return _SatuanPacks; }
            private set
            {
                if (SatuanPacks == value) return;
                _SatuanPacks = value;
                FirePropertyChanged("SatuanPacks");
            }
        }


        public ObservableCollection<SatuanDTO> SatuanUnits
        {
            get { return _SatuanUnits; }
            private set
            {
                if (SatuanUnits == value) return;
                _SatuanUnits = value;
                FirePropertyChanged("SatuanUnits");
            }
        }


        public ObservableCollection<WarehouseDTO> Warehouses
        {
            get { return _Warehouses; }
            private set
            {
                if (Warehouses == value) return;
                _Warehouses = value;
                FirePropertyChanged("Warehouses");
            }
        }

        public bool NoLogFocus
        {
            get { return _NoLogfocus; }
            set
            {
                if (NoLogFocus == value) return;
                _NoLogfocus = value;
                FirePropertyChanged("NoLogFocus");
            }
        }


        public ICommand OnPageChanged { get; set; }
        public ICommand Save { get; set; }
        public ICommand New { get; set; }
        public ICommand Edit { get; set; }
        public ICommand Unload { get; set; }
        public ICommand SearchCommand { get; set; }
        public ICommand SearchResultCommand { get; set; }
        public ICommand CancelCommand { get; set; }
        public ICommand GetPOCommand { get; set; }
        public ICommand PrintCommand { get; set; }


        public List<string> Errors
        {
            get { return _errors; }
            private set
            {
                if (Errors == value) return;
                _errors = value;
                FirePropertyChanged("Errors");
            }
        }

        public Visibility MessageVisibility
        {
            get { return _messageVisibility; }
            private set
            {
                if (MessageVisibility == value) return;
                _messageVisibility = value;
                FirePropertyChanged("MessageVisibility");
            }
        }

        private void PrepareEdit()
        {
            BTB = (BTBDTO) Navigation.Args;
            GetBtb(BTB);
            CekTransaksi();
        }

        private void PrepareAdd()
        {
            //GetLastNoBTB();
            GetPurchaseOrderList();
            GetSatuanPackList();
            GetWarehouseList();
            GetSupplierList();
            BTB = new BTBDTO();
            BTB.BtbDetails = new ObservableCollection<BTBDetailDTO>();
            var BTBDetail = new BTBDetailDTO();
            BTB.BtbDetails.Add(BTBDetail);
            GetItemList();
            //CekTransaksi();
        }

        private void GetBtb(BTBDTO param)
        {
            IsBusy = true;
            client.GetBTBCompleted += client_GetBTBCompleted;
            client.GetBTBAsync(param.NoBtb);
        }

        private void client_GetBTBCompleted(object sender, GetBTBCompletedEventArgs e)
        {
            client.GetBTBCompleted -= client_GetBTBCompleted;
            BTB = e.Result;
            if (BTB.Status == Status.Void || BTB.Status == Status.Close)
            {
                IsEnabled = false;
            }

            GetSatuanPackList();
            GetWarehouseList();
            GetPurchaseOrderList();
            POTemp = BTB.PurchaseOrder;

            if (BTB.BtbDetails == null)
                BTB.BtbDetails = new ObservableCollection<BTBDetailDTO>();
            if (BTB.BtbDetails.Count == 0)
                BTB.BtbDetails.Add(new BTBDetailDTO());

            foreach (BTBDetailDTO btbDetail in BTB.BtbDetails)
            {
                btbDetail.Items = new ObservableCollection<ItemDTO>();
                btbDetail.Items.Add(btbDetail.Item);
            }

            GetItemList();

            IsBusy = false;
        }


        public void Complete(Object param)
        {
            OnSearchCompleted(param);
        }

        private void BTB_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (((PagedCollectionView) sender).SortDescriptions.Count > 0)
            {
                if (((PagedCollectionView) sender).SortDescriptions[0].PropertyName.ToLower() == "no") return;

                PropertySort = ((PagedCollectionView) sender).SortDescriptions[0].PropertyName;
                if (string.IsNullOrEmpty(OrderType))
                {
                    OrderType = "ASC";
                }
                else
                {
                    OrderType = OrderType == "ASC" ? OrderType = "DESC" : OrderType = "ASC";
                }
                GetList(1, PropertySort);
            }
        }


        public void SaveBTB(Object btb)
        {
           
            if (BTB.BtbDetails.Count == 1)
            {
                //Bila tidak ada yang dipilih di detail maka details harus dihapus
                if (BTB.BtbDetails[0].Item == null)
                    BTB.BtbDetails.Clear();
            }
            Validate();
            if (Errors.Count > 0) return;
            //BTB.created_by = GlobalVar.User.UserID;
            //BTB.modified_by = GlobalVar.User.UserID;
            client.SaveCompleted += client_SaveCompleted;
            IsBusy = true;
            client.SaveAsync(BTB, mode);
        }

        private void client_SaveCompleted(object sender, SaveCompletedEventArgs e)
        {
            if (e.Error != null) Validate(e.Error.ToString());
            client.SaveCompleted -= client_SaveCompleted;
            mode = (Mode) e.UserState;
            if (e.Result)
            {
                IsBusy = false;
                ClearTransaksi(mode);
                mode = Mode.Idle;
                Navigation.MyNavigation.Navigate(new Uri("/EXT:BTB.dll/Index", UriKind.Relative));
            }
            else
            {
                IsBusy = false;
                MessageBox.Show("Simpan Gagal, periksa data Anda!");
            }
        }


        public void GetList(int? page, string sortProp)
        {
            IsBusy = true;
            client.GetListCompleted += client_GetListCompleted;
            client.GetListAsync(page ?? 1, sortProp, OrderType);
        }

        private void client_GetListCompleted(object sender, GetListCompletedEventArgs e)
        {
            RecordCount = e.recordCount;
            if (PageSources == null) CreatePageNumber();
            client.GetListCompleted -= client_GetListCompleted;
            BTBs = new PagedCollectionView(e.Result);
            IsBusy = false;
            Complete(this);
        }


        private void NewBTB(Object param)
        {
            mode = Mode.Add;
            Navigation.MyNavigation = (NavigationService) param;
            Navigation.MyNavigation.Navigate(new Uri("/EXT:BTB.dll/frmAdd", UriKind.Relative));
        }


        private void SearchBTB(Object param)
        {
            mode = Mode.Search;
            frmSearch = new Search();
            frmSearch.Show();
        }


        private void SearchResult(Object param)
        {
            criteria = new Dictionary<string, object>();

            foreach (PropertyInfo prop in BTB.GetType().GetProperties())
            {
                if (prop.PropertyType == typeof (Decimal))
                {
                    if ((Decimal) prop.GetValue(BTB, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int32))
                {
                    if ((Int32) prop.GetValue(BTB, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Int64))
                {
                    if ((Int64) prop.GetValue(BTB, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (Double))
                {
                    if ((Double) prop.GetValue(BTB, null) == 0) continue;
                }
                if (prop.PropertyType == typeof (String))
                {
                    if (String.IsNullOrEmpty((String) prop.GetValue(BTB, null))) continue;
                }
                if (prop.PropertyType == typeof (DateTime))
                {
                    if (prop.GetValue(BTB, null).ToString().Contains("0001")) continue;
                }
                if (prop.GetValue(BTB, null) == null) continue;
                if (prop.PropertyType.Name == "No") continue;

                if (prop.PropertyType.Name.ToLower().Contains("dto"))
                {
                    foreach (PropertyInfo propertyInfo in prop.GetValue(BTB, null).GetType().GetProperties()
                        )
                    {
                        if (propertyInfo.Name.ToLower().Contains("id") || propertyInfo.Name.ToLower().Contains("kode") ||
                            propertyInfo.Name.ToLower().Contains("serial") ||
                            propertyInfo.Name.ToLower().Contains("code") || propertyInfo.Name.ToLower().Contains("number"))
                        {
                            criteria.Add(prop.Name, propertyInfo.GetValue(prop.GetValue(BTB, null), null));
                            break;
                        }
                    }
                }
                else
                {
                    criteria.Add(prop.Name, prop.GetValue(BTB, null));
                }
            }

            expression = string.Empty;
            if (frmSearch.rblOr.IsChecked ?? false) expression = "OR";
            else expression = "AND";
            BTBSearch(criteria, expression,1);
        }

        private void BTBSearch(Dictionary<String, Object> criteria, string expression, int page)
        {
            if (criteria.ContainsKey("Status")) criteria.Remove("Status");
            frmSearch.DialogResult = true;
            IsBusy = true;
            Complete(this);
            client.GetListByCriteriaCompleted += client_GetListByCriteriaCompleted;
            client.GetListByCriteriaAsync(criteria, expression, page,criteria);
        }

        private void client_GetListByCriteriaCompleted(object sender, GetListByCriteriaCompletedEventArgs e)
        {
            client.GetListByCriteriaCompleted -= client_GetListByCriteriaCompleted;
            BTBs = new PagedCollectionView(e.Result);
            if (RecordCount != e.recordCount)
            {
                RecordCount = e.recordCount;
                CreatePageNumber();
            }
            IsBusy = false;
            criteria = (Dictionary<String, Object>)e.UserState;
        }


        private void GetPurchaseOrderList()
        {
            PurchaseOrderClient.GetAllPurchaseOrderCompleted += PurchaseOrderClient_GetAllPurchaseOrderCompleted;
            PurchaseOrderClient.GetAllPurchaseOrderAsync();
        }

        private void PurchaseOrderClient_GetAllPurchaseOrderCompleted(object sender,
                                                                      GetAllPurchaseOrderCompletedEventArgs e)
        {
            PurchaseOrderClient.GetAllPurchaseOrderCompleted -= PurchaseOrderClient_GetAllPurchaseOrderCompleted;
            e.Result.Insert(0, new PurchaseOrderDTO {PONumber = "--Pilih--"});
            PurchaseOrders = e.Result;

            //Mapping PO Detail);
            foreach (PurchaseOrderDTO purchaseOrder in PurchaseOrders)
            {
                purchaseOrder.PurchaseOrderDetails = new ObservableCollection<PurchaseOrderDetailDTO>();
                PurchaseOrderDTO PO =
                    e.Result.FirstOrDefault(x => x.PONumber == purchaseOrder.PONumber);

                foreach (PurchaseOrderDetailDTO PODetail in PO.PurchaseOrderDetails)
                    purchaseOrder.PurchaseOrderDetails.Add(
                        PODetail);
            }


            //Edit Mode
            if (BTB != null)
            {
                if (BTB.PurchaseOrder == null) return;
                PurchaseOrders.Add(new PurchaseOrderDTO {PONumber = BTB.PurchaseOrder.PONumber});
                BTB.PurchaseOrder =
                    PurchaseOrders.FirstOrDefault(s => s.PONumber == BTB.PurchaseOrder.PONumber);
                BTB.PurchaseOrder = POTemp;
            }
        }

        private void GetSupplierList()
        {
            SupplierClient.GetAllSupplierCompleted += SupplierClient_GetAllSupplierCompleted;
            SupplierClient.GetAllSupplierAsync();
        }

        private void SupplierClient_GetAllSupplierCompleted(object sender, GetAllSupplierCompletedEventArgs e)
        {
            SupplierClient.GetAllSupplierCompleted -= SupplierClient_GetAllSupplierCompleted;
            Suppliers = e.Result;

            if (BTB != null)
            {
                if (BTB.Supplier == null) return;
                BTB.Supplier =
                    Suppliers.FirstOrDefault(s => s.SupplierId == BTB.Supplier.SupplierId);
            }
        }


        private void CreatePageNumber()
        {
            Pages = new ObservableCollection<int>();
            for (int i = 0; i < RecordCount; i++)
            {
                Pages.Add(i);
            }
            PageSources = new PagedCollectionView(Pages);
        }


        private void PageIndexChanged(Object pageIndex)
        {
            //Jika Pertama kali jangan di Getlagi
            BTB = null;
            if (BTBs != null && CurrentPage != (int) pageIndex)
            {
                CurrentPage = (int) pageIndex;
                if (mode == Mode.Search)
                    BTBSearch(criteria, expression, (int)pageIndex + 1);
                else if (String.IsNullOrEmpty(PropertySort))
                    GetList((int) pageIndex + 1, null);
                else GetList((int) pageIndex + 1, PropertySort);
            }
        }


        public bool CanPageIndexChanged(Object param)
        {
            return true;
        }


        public bool CanSave(Object param)
        {
            return true;
        }


        public bool CanNew(Object param)
        {
            return true;
        }

        public bool CanEdit(Object param)
        {
            return true;
        }


        public bool CanUnload(Object param)
        {
            return true;
        }


        public bool CanSearch(Object param)
        {
            return true;
        }

        public bool CanSearchResult(Object param)
        {
            return true;
        }

        public bool CanCancelCommand(Object param)
        {
            return true;
        }

        public bool CanGetPOCommand(Object param)
        {
            return true;
        }

        public bool CanPrintCommand(Object param)
        {
            return true;
        }


        public void Release(Object param)
        {
            param = null;
            BTB = null;
            OrderType = null;
            PropertySort = null;
            mode = Mode.Idle;
        }


        public void Refresh()
        {
            if (BTBs == null)
                GetList(1, null);
            else
                Complete(this);
        }


        public void Validate(string error = null)
        {
            Errors = new List<string>();
            //if (string.IsNullOrEmpty(BTB.NoBtb))
            //    Errors.Add("Nomor BTB tidak boleh kosong");

            if (BTB.PurchaseOrder == null)
                Errors.Add("Purchase Order harus diisi!");

            foreach (BTBDetailDTO btbDetail in BTB.BtbDetails)
            {
                if (btbDetail.SatuanUnit == null)
                    Errors.Add(btbDetail.NoLog + " Satuan Unit belum diisi!");

                if (btbDetail.Warehouse == null)
                    Errors.Add(btbDetail.NoLog + " Warehouse belum diisi!");

                if (btbDetail.SatuanPack == null)
                    Errors.Add(btbDetail.NoLog + " Satuan Pack belum diisi!");

                if (btbDetail.Item == null)
                    Errors.Add(btbDetail.NoLog + " Item belum diisi!");

                if (btbDetail.QtyUnit <= 0)
                    Errors.Add(btbDetail.NoLog + " Qty tidak valid!");
            }

            //validasi item BTB Detail harus sesuai dengan SubGroup PO belakangan
            //foreach (BTBDetailDTO btbDetail in BTB.BtbDetails)
            //{
            //    if (!
            //        BTB.PurchaseOrder.PurchaseOrderDetails.Any(
            //            x => x.SubGroup.SubGroupID == btbDetail.Item.SubGroup.SubGroupID))
            //        Errors.Add("NoLog " + btbDetail.NoLog + " itemnya tidak sesuai dengan PO!");
            //}

            if (BTB.Supplier == null)
                Errors.Add("Supplier Belum diisi!");
            if (!string.IsNullOrEmpty(error))
                Errors.Add(error);

            if (Errors.Count > 0)
            {
                MessageVisibility = Visibility.Visible;
            }
            else
            {
                MessageVisibility = Visibility.Collapsed;
            }
        }

        public void Cancel(Object param)
        {
            MessageBoxResult res = MessageBox.Show("Are You Sure Want to Cancel ?", "Confirmation",
                                                   MessageBoxButton.OKCancel);
            if (res == MessageBoxResult.OK)
            {
                if (! IsUsed) ClearTransaksi(mode);
                mode = Mode.Idle;
                Navigation.MyNavigation.GoBack();
            }
        }

        private void GetLastNoBTB()
        {
            client = new BTBServicesClient();
            client.GetLastBTBNoCompleted += client_GetLastBTBNoCompleted;
            client.GetLastBTBNoAsync();
        }

        private void client_GetLastBTBNoCompleted(object sender, GetLastBTBNoCompletedEventArgs e)
        {
            client.GetLastBTBNoCompleted -= client_GetLastBTBNoCompleted;
            string res = e.Result;
            string formatSO = "0000";
            string kodeSO;
            if (e.Result.Length <= 4)
            {
                res = formatSO;
                kodeSO = e.Result;
            }
            else
            {
                res = e.Result.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries)[2];
                kodeSO = e.Result.Split(new[] {"/"}, StringSplitOptions.RemoveEmptyEntries)[0];
            }
            string soNum = formatSO.Substring(0, formatSO.Length - (int.Parse(res) + 1).ToString().Length) +
                           (int.Parse(res) + 1);

            BTB.NoBtb = kodeSO + "/" + DateTime.Now.Year + "/" + soNum;
        }


        public void GetPO(Object param)
        {
            var PO = param as PurchaseOrderDTO;
            if (PO == null || PO.PONumber.ToLower().Contains("pilih")) return;
            string PONo = ((PurchaseOrderDTO) param).PONumber;
            PurchaseOrderClient.GetPurchaseOrderCompleted += PurchaseOrderClient_GetPurchaseOrderCompleted;
            PurchaseOrderClient.GetPurchaseOrderAsync(PONo);
        }

        private void PurchaseOrderClient_GetPurchaseOrderCompleted(object sender, GetPurchaseOrderCompletedEventArgs e)
        {
            BTB.PurchaseOrder = e.Result;
            PurchaseOrderClient.GetPurchaseOrderCompleted -= PurchaseOrderClient_GetPurchaseOrderCompleted;
            if (BTB != null)
                BTB.Supplier = e.Result.Supplier;
        }

        public void GetItemByName(Object param)
        {
            if (param.GetType() == typeof (BTBDetailDTO))
            {
                BtbDetailCurrent = param as BTBDetailDTO;
                ItemClient.GetItemByNameCompleted += ItemClient_GetItemByNameCompleted;
                ItemClient.GetItemByNameAsync(BtbDetailCurrent.Item.ItemName);
            }
            else
            {
                ItemClient.GetItemByNameCompleted += ItemClient_GetItemByNameCompleted;
                ItemClient.GetItemByNameAsync(param.ToString());
            }
        }

        private void ItemClient_GetItemByNameCompleted(object sender, GetItemByNameCompletedEventArgs e)
        {
            ItemClient.GetItemByNameCompleted -= ItemClient_GetItemByNameCompleted;
            Items = e.Result;
        }

      

        public void Print(Object param)
        {
            Navigation.MyNavigation.Navigate(new Uri("/BTB/PrintPreviewBTB", UriKind.Relative));
            Navigation.Args = param;
        }

        public void GetSatuanPackList()
        {
            SatuanClient.GetListByCriteriaCompleted +=
                SatuanClient_GetListByCriteriaCompleted;
            SatuanClient.GetListByCriteriaAsync(new Dictionary<string, object>(), null, 1);
        }

        private void SatuanClient_GetListByCriteriaCompleted(object sender,
                                                             SatuanServices.GetListByCriteriaCompletedEventArgs
                                                                 e)
        {
            SatuanClient.GetListByCriteriaCompleted -=
                SatuanClient_GetListByCriteriaCompleted;

            SatuanPacks = e.Result;
            SatuanUnits = e.Result;
            RefreshSatuan();
        }


        public void GetWarehouseList()
        {
            WarehouseServicesClient.GetListByCriteriaCompleted +=
                WarehouseClient_GetListByCriteriaCompleted;
            WarehouseServicesClient.GetListByCriteriaAsync(new Dictionary<string, object>(), null, 1);
        }

        private void WarehouseClient_GetListByCriteriaCompleted(object sender,
                                                                WarehouseServices.GetListByCriteriaCompletedEventArgs e)
        {
            WarehouseServicesClient.GetListByCriteriaCompleted -=
                WarehouseClient_GetListByCriteriaCompleted;
            Warehouses = e.Result;
            RefreshWarehouse();
        }

        private void RefreshWarehouse()
        {
            if (BTB != null)
                foreach (BTBDetailDTO BTBDetail in BTB.BtbDetails)
                {
                    BTBDetail.Warehouses = Warehouses;
                    if (BTBDetail.Warehouse != null)
                    {
                        BTBDetail.Warehouse =
                            Warehouses.FirstOrDefault(s => s.KodeWarehouse == BTBDetail.Warehouse.KodeWarehouse);
                    }
                }
        }

        private void RefreshSatuan()
        {
            if (BTB != null)
                foreach (BTBDetailDTO BTBDetail in BTB.BtbDetails)
                {
                    BTBDetail.SatuanPacks = SatuanPacks;
                    BTBDetail.SatuanUnits = SatuanPacks;
                    if (BTBDetail.SatuanPack != null)
                    {
                        BTBDetail.SatuanPack =
                            SatuanPacks.FirstOrDefault(s => s.KodeSatuan == BTBDetail.SatuanPack.KodeSatuan);
                        BTBDetail.SatuanUnit =
                            SatuanUnits.FirstOrDefault(s => s.KodeSatuan == BTBDetail.SatuanUnit.KodeSatuan);
                    }
                }
        }

        public void SendEmail(Object param)
        {
            ChooseDestination chooseDestination = new ChooseDestination();
            chooseDestination.Show();
            EventAggregator.RegisterMessage("SendDestination", (x) =>
            {
                IsBusy = true;
                client.SendEmailCompleted += client_SendEmailCompleted;
                client.SendEmailAsync(param as BTBDTO, (x as WarehouseDTO).EmailFolder);
            });
        }

        private void client_SendEmailCompleted(object sender, SendEmailCompletedEventArgs e)
        {
            IsBusy = false;
            client.SendEmailCompleted -= client_SendEmailCompleted;
            if (e.Result) MessageBox.Show("Pengiriman Selesai");
        }

        public void CekTransaksi()
        {
            ApplicationService.IsTransactionUsedCompleted += ApplicationService_IsTransactionUsedCompleted;
            if (string.IsNullOrEmpty(BTB.NoBtb))
            {
                ApplicationService.IsTransactionUsedAsync(BTB.ToString(), GlobalVar.User, mode);
                GlobalVar.CurrentTransaction = BTB.ToString();
            }
            else
            {
                ApplicationService.IsTransactionUsedAsync(BTB.NoBtb, GlobalVar.User, mode);
                GlobalVar.CurrentTransaction = BTB.NoBtb;
            }
        }

        private void ApplicationService_IsTransactionUsedCompleted(object sender, IsTransactionUsedCompletedEventArgs e)
        {
            ApplicationService.IsTransactionUsedCompleted -= ApplicationService_IsTransactionUsedCompleted;
            IsUsed = e.Result;
            mode = (Mode) e.UserState;
            if (IsUsed)
            {
                MessageBox.Show("Transaksi sedang digunakan!");
                if (mode == Mode.Add) //If Add Mode
                {
                    mode = Mode.Idle;
                    Navigation.MyNavigation.Navigate(new Uri("/Btb/Index", UriKind.Relative));
                }
                else //Edit Mode just view Only
                {
                    IsEnabled = false;
                }
            }
        }

        private void ClearTransaksi(Mode mode)
        {
            ApplicationService.ClearTransactionCompleted += ApplicationService_ClearTransactionCompleted;
            if (mode == Mode.Add)
                ApplicationService.ClearTransactionAsync(BTB.ToString(), GlobalVar.User);
            else
                ApplicationService.ClearTransactionAsync(BTB.NoBtb, GlobalVar.User);
        }

        private void ApplicationService_ClearTransactionCompleted(object sender, AsyncCompletedEventArgs e)
        {
            ApplicationService.ClearTransactionCompleted -= ApplicationService_ClearTransactionCompleted;
        }

        public ICommand LoadDetailFromFileCommand { get; set; }
        public bool CanLoadDetailFromFile(Object param)
        {
            return true;
        }

        public void LoadDetailFromFile(Object param)
        {
            ImportHelper importHelper = new ImportHelper();
            IEnumerable<List<dynamic>> sourcesOld;
            importHelper.BrowseExcelFile(out sourcesOld);
            var sources = importHelper.LoadExcellFile(importHelper.listSheetNames.FirstOrDefault());
            BTB.BtbDetails.Clear();
            if (sourcesOld == null || sourcesOld.Count() == 0)
            {

                if (sources != null)
                    foreach (dynamic data in sources)
                    {
                        var btbDetail = new BTBDetailDTO();
                        btbDetail.Items = new ObservableCollection<ItemDTO>();
                        var item = new ItemDTO() { ItemId = data.K };
                        if (itemDicts.ContainsKey(item.ItemId))
                            item = itemDicts[item.ItemId];

                        btbDetail.Items.Add(item);
                        btbDetail.SatuanPacks = SatuanPacks;
                        btbDetail.SatuanUnits = SatuanUnits;
                        btbDetail.Warehouses = Warehouses;

                        btbDetail.NoBtb = BTB.NoBtb;
                        btbDetail.NoLog = data.A;
                        if (string.IsNullOrEmpty(btbDetail.NoLog)) continue;
                        btbDetail.NoBundle = int.Parse(data.B);
                        btbDetail.Description = data.C;
                        btbDetail.QtyPack = decimal.Parse(data.D);
                        //btbDetail.QtyUnit = decimal.Parse(data.E);
                        btbDetail.Panjang = decimal.Parse(data.F);
                        btbDetail.Lebar = decimal.Parse(data.G);
                        btbDetail.Tinggi = decimal.Parse(data.H);
                        btbDetail.KodeMasuk = data.I;
                        btbDetail.Item = btbDetail.Items.FirstOrDefault(x => x.ItemId == data.J);
                        btbDetail.SatuanPack = btbDetail.SatuanPacks.FirstOrDefault(x => x.KodeSatuan == data.K);
                        btbDetail.SatuanUnit = btbDetail.SatuanUnits.FirstOrDefault(x => x.KodeSatuan == data.L);
                        btbDetail.Warehouse = btbDetail.Warehouses.FirstOrDefault(x => x.KodeWarehouse == data.M);
                        btbDetail.KodePallet = data.N;
                        GetQtyUnit(btbDetail);
                        btbDetail.QtyUnit = btbDetail.Item.IsRounded
                                                   ? btbDetail.QtyUnit.Round(2,MidpointRounding.AwayFromZero)
                                                   : btbDetail.QtyUnit.Round(4, MidpointRounding.AwayFromZero);
                        BTB.BtbDetails.Add(btbDetail);
                    }


            }else
            {
                int i = 0;
                foreach (var data in sourcesOld)
                {
                    if (i > 0)
                    {
                        var btbDetail = new BTBDetailDTO();
                        btbDetail.Items = new ObservableCollection<ItemDTO>();
                        var item = new ItemDTO() { ItemId = data[9].ToString() };
                        if (itemDicts.ContainsKey(item.ItemId))
                            item = itemDicts[item.ItemId];
                        else
                            MessageBox.Show("ItemID " + item.ItemId +
                                            "tidak ada di Master Item!");
                        btbDetail.Items.Add(item);
                        btbDetail.SatuanPacks = SatuanPacks;
                        btbDetail.SatuanUnits = SatuanUnits;
                        btbDetail.Warehouses = Warehouses;

                        btbDetail.NoBtb = BTB.NoBtb;
                        btbDetail.NoLog = data[0];
                        if (string.IsNullOrEmpty(btbDetail.NoLog)) continue;
                        btbDetail.NoBundle = Convert.ToInt32(data[1]);
                        btbDetail.Description = data[2].ToString();
                        btbDetail.QtyPack = Convert.ToDecimal(data[3]);
                        //btbDetail.QtyUnit = decimal.Parse(data.E);
                        btbDetail.Panjang = Convert.ToDecimal(data[5]);
                        btbDetail.Lebar = Convert.ToDecimal(data[6]);
                        btbDetail.Tinggi = Convert.ToDecimal(data[7]);
                        btbDetail.KodeMasuk = data[8] != null ? (string)data[9].ToString() : string.Empty;
                        btbDetail.Item =
                            btbDetail.Items.FirstOrDefault(
                                x => x.ItemId == data[9].ToString());
                        btbDetail.SatuanPack =
                            btbDetail.SatuanPacks.FirstOrDefault(
                                x => x.KodeSatuan == data[10].ToString());
                        btbDetail.SatuanUnit =
                            btbDetail.SatuanUnits.FirstOrDefault(
                                x => x.KodeSatuan == data[11].ToString());
                        btbDetail.Warehouse =
                            btbDetail.Warehouses.FirstOrDefault(
                                x => x.KodeWarehouse == data[12].ToString());
                        btbDetail.KodePallet = data[13].ToString();
                        GetQtyUnit(btbDetail);
                        btbDetail.QtyUnit = btbDetail.Item.IsRounded
                                                ? btbDetail.QtyUnit.Round(2, MidpointRounding.AwayFromZero)
                                                : btbDetail.QtyUnit.Round(4, MidpointRounding.AwayFromZero);
                        BTB.BtbDetails.Add(btbDetail);
                    }
                    i++;
                }


            }
           
        }

        public void GetQtyUnit(BTBDetailDTO param)
        {
            Decimal pengali = 1;
            if (param.SatuanUnit != null && param.SatuanUnit.Pengali > 0)
                pengali = param.SatuanUnit.Pengali;
            param.QtyUnit = param.QtyPack *
                                    (param.Panjang * param.Lebar *
                                     param.Tinggi) / pengali;
        }

        public void GetItemList()
        {
            ItemClient.GetAllItemCompleted += new EventHandler<GetAllItemCompletedEventArgs>(ItemClient_GetAllItemCompleted);
            ItemClient.GetAllItemAsync();
        }

        void ItemClient_GetAllItemCompleted(object sender, GetAllItemCompletedEventArgs e)
        {
            ItemClient.GetAllItemCompleted -= new EventHandler<GetAllItemCompletedEventArgs>(ItemClient_GetAllItemCompleted);
            foreach (var btbDetail in BTB.BtbDetails)
            {
                btbDetail.Items = e.Result;
                if (btbDetail.Item != null)
                    btbDetail.Item = e.Result.FirstOrDefault(x => x.ItemId == btbDetail.Item.ItemId);
            }
        }

        protected Dictionary<string, ItemDTO> itemDicts
        {
            get;
            set;
        }
    }


    public class BTBWrapViewModel : ViewModelBase
    {
        private readonly ItemServicesClient ItemClient;
        private readonly SatuanServicesClient SatuanClient;
        private readonly WarehouseServicesClient WarehouseServicesClient;
        private readonly BTBServicesClient client;
        private BTBDetailDTO _BTBDetail;
        private ObservableCollection<ItemDTO> _Items;
        private ObservableCollection<PalletDTO> _Pallets;
        private ObservableCollection<SatuanDTO> _SatuanPacks;
        private ObservableCollection<SatuanDTO> _SatuanUnits;
        private ObservableCollection<WarehouseDTO> _Warehouses;
        private InventoryServices.InventoryServiceClient InventoryClient;


        public BTBWrapViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                EditCommand = new DelegateCommand(Edit, CanEditCommand);
                DeleteCommand = new DelegateCommand(Delete, CanDeleteCommand);
                client = new BTBServicesClient();
                ItemClient = new ItemServicesClient();
                SatuanClient = new SatuanServicesClient();
                WarehouseServicesClient = new WarehouseServicesClient();
                InventoryClient = new InventoryServiceClient();

                AddDetailCommand = new DelegateCommand(AddBTBDetail, CanAddDetailCommand);
                DeleteDetailCommand = new DelegateCommand(DeleteBTBDetail, CanDeleteDetailCommand);
                GetQtyUnitCommand = new DelegateCommand(GetQtyUnit, CanGetQtyUnit);

                if (BTBViewModel.mode == Mode.Add || BTBViewModel.mode == Mode.Edit)
                {
                }
            }
        }

        public BTBViewModel BTBViewModel { get; set; }


        public ICommand EditCommand { get; set; }
        public ICommand DeleteCommand { get; set; }
        public ICommand AddDetailCommand { get; set; }
        public ICommand DeleteDetailCommand { get; set; }
        public ICommand GetQtyUnitCommand { get; set; }


        public ObservableCollection<ItemDTO> Items
        {
            get { return _Items; }
            private set
            {
                if (Items == value) return;
                _Items = value;
                FirePropertyChanged("Items");
            }
        }


        public ObservableCollection<PalletDTO> Pallets
        {
            get { return _Pallets; }
            private set
            {
                if (Pallets == value) return;
                _Pallets = value;
                FirePropertyChanged("Pallets");
            }
        }


        public BTBDetailDTO BTBDetail
        {
            get { return _BTBDetail; }
            private set
            {
                if (BTBDetail == value) return;
                _BTBDetail = value;
                FirePropertyChanged("BTBDetail");
            }
        }

        public bool CanEditCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteCommand(Object param)
        {
            return true;
        }

        public bool CanAddDetailCommand(Object param)
        {
            return true;
        }

        public bool CanDeleteDetailCommand(Object param)
        {
            return true;
        }


        public void Edit(Object param)
        {
            BTBViewModel.mode = Mode.Edit;
            Navigation.Args = param;
            Navigation.MyNavigation.Navigate(new Uri("/EXT:BTB.dll/frmAdd", UriKind.Relative));
            
        }

        public void Delete(Object param)
        {          
            DeleteConfirmation deleteConfirmation = new DeleteConfirmation();
            deleteConfirmation.Show();
            EventAggregator.RegisterMessage("ApprovalSucceeded", (x) =>
            {
                deleteConfirmation.Close();
                client.DeleteCompleted += client_DeleteCompleted;
                client.DeleteAsync((BTBDTO)param);
            });

        }

        private void client_DeleteCompleted(object sender, AsyncCompletedEventArgs e)
        {
            client.DeleteCompleted -= client_DeleteCompleted;
            MessageBox.Show("Delete Success!");
            BTBViewModel.mode = Mode.Idle;
            var VM = new BTBViewModel();
        }

        public void AddBTBDetail(Object param)
        {
            if (param == null) param = BTBViewModel.BTB.BtbDetails[BTBViewModel.BTB.BtbDetails.Count - 1];
            var btbdetail = param as BTBDetailDTO;
            BTBDetail = new BTBDetailDTO
                            {
                                Items = btbdetail.Items,
                                Item = new ItemDTO {ItemId = btbdetail.Item.ItemId, ItemName = btbdetail.Item.ItemName},
                                QtyPack = btbdetail.QtyPack,
                                SatuanPacks = btbdetail.SatuanPacks,
                                SatuanUnits = btbdetail.SatuanUnits,
                                Warehouses = btbdetail.Warehouses,
                                Warehouse = btbdetail.Warehouse,
                                Pallets = btbdetail.Pallets,
                                KodePallet = btbdetail.KodePallet,
                                SatuanPack = btbdetail.SatuanPack,
                                SatuanUnit = btbdetail.SatuanUnit,
                                KodeMasuk = btbdetail.KodeMasuk,
                                Description = btbdetail.Description
                            };
            BTBViewModel.BTB.BtbDetails.Add(BTBDetail);
        }

        public void DeleteBTBDetail(Object param)
        {
            var BTBDetail = (BTBDetailDTO) param;
            if (BTBViewModel.BTB.BtbDetails.Count > 1)
                {
                    if (param == null)
                        BTBDetail = BTBViewModel.BTB.BtbDetails[BTBViewModel.BTB.BtbDetails.Count - 1];
                    BTBViewModel.BTB.BtbDetails.Remove(BTBDetail);
                }
        }

        public bool CanGetInventoryCommand(Object param)
        {
            return true;
        }

        public bool CanGetQtyUnit(Object param)
        {
            return true;
        }

        public void GetQtyUnit(Object param)
        {
            BTBDetail = (BTBDetailDTO)param;
            if (BTBDetail.Item == null)return;
            BTBDetail.SatuanUnit = BTBDetail.SatuanUnits.FirstOrDefault(x =>    x.KodeSatuan == BTBDetail.Item.Satuan.KodeSatuan);
            BTBDetail.SatuanPack = BTBDetail.SatuanPacks.FirstOrDefault(x => x.KodeSatuan == BTBDetail.Item.SatuanPack.KodeSatuan);

            Decimal pengali = 1;
            if (BTBDetail.SatuanUnit != null && BTBDetail.SatuanUnit.Pengali > 0)
                pengali = BTBDetail.SatuanUnit.Pengali;
            BTBDetail.QtyUnit = BTBDetail.QtyPack*
                                (BTBDetail.Panjang*BTBDetail.Lebar*
                                 BTBDetail.Tinggi)/pengali;

            BTBDetail.QtyUnit = BTBDetail.Item.IsRounded
                                             ? BTBDetail.QtyUnit.Round(2, MidpointRounding.AwayFromZero)
                                             : BTBDetail.QtyUnit.Round(4, MidpointRounding.AwayFromZero);
        }
      
    }
}